﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
using System.Web.SessionState;

public partial class RenderImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        new PngRenderDispatcher().processRequest(this.Request, this.Response, this.Session);
    }
}

public class PngRenderDispatcher : com.wiris.servlet.Dispatcher
{
    private static int counter = 0;
    private static long firstRequestTimestamp = DateTime.Now.Ticks;

    public override void countUsage()
    {
        counter++;
    }

    public override long getFirstRequestTimestamp()
    {
        return firstRequestTimestamp;
    }

    public override int getUsageCounter()
    {
        return counter;
    }

    public override void processRequest(HttpRequest request, HttpResponse response, HttpSessionState session)
    {
        this.countUsage();
        string mathml = request["matml"];
        if (mathml == null)
        {
            mathml = request["mml"];
        }
        string latex = request["latex"];
        byte[] buffer = com.wiris.editor.services.PublicServices.getInstance().renderPng(mathml, latex, PngRenderDispatcher.getProperties(request), null);
        response.ContentType = "image/png";
        response.AddHeader("Content-Length", buffer.Length.ToString());
        response.OutputStream.Write(buffer, 0, buffer.Length);
    }

    public static Dictionary<string, string> getProperties(HttpRequest request)
    {
        Dictionary<string, string> properties = new Dictionary<string, string>();
        parseParams(request.QueryString, properties);
        parseParams(request.Form, properties);
        properties["maxZoom"] = com.wiris.system.TypeTools.floatToString(25.0);
        return properties;
    }

    public static void parseParams(NameValueCollection collection, Dictionary<string, string> properties)
    {
        foreach (string str in collection.Keys)
        {
            if (((str != null) && (str != "mml")) && (str != "latex"))
            {
                properties[str.ToLower()] = collection[str];
            }
        }
    }

}